package cn.jolyoulu.common.core.utils.monitor;

import lombok.extern.slf4j.Slf4j;
import cn.jolyoulu.common.core.entity.MemoryInfo;
import cn.jolyoulu.common.core.entity.SystemInfo;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.*;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class JmxUtils {
    //mBean
    private static final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    //操作系统
    private static final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    //编译系统
    private static final CompilationMXBean compilationMXBean = ManagementFactory.getCompilationMXBean();
    //内存
    private static final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

    /**
     * 获取操作系统信息
     */
    public static SystemInfo systemInfo(){
        String osName = operatingSystemMXBean.getName();
        String osVersion = operatingSystemMXBean.getVersion();
        int processors = operatingSystemMXBean.getAvailableProcessors();
        String compilationMXBeanName = compilationMXBean.getName();
        return new SystemInfo(osName,compilationMXBeanName,osVersion,processors);
    }

    /**
     * 获取内存以及垃圾回收信息
     */
    public static MemoryInfo memoryInfo(){
        MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        //内存使用情况
        long max = heapMemoryUsage.getMax();
        long used = heapMemoryUsage.getUsed();
        //垃圾收集器信息
        List<GarbageCollectorMXBean> gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
        String gcNames = gcMXBeans.stream()
                .map(MemoryManagerMXBean::getName)
                .collect(Collectors.joining(","));
        return new MemoryInfo(max / 1024 / 1024,used / 1024 / 1024,gcNames);
    }

    /**
     * 向Jxm注入一个Bean
     */
    public static <T> void registerMBean(String objectName, T mbean){
        try {
            mBeanServer.registerMBean(mbean,new ObjectName(objectName));
        }catch (Exception e){
            log.error("registerMBean error",e);
        }
    }
}
